<template>
  <basic-container>
    <avue-crud ref="crud"
               v-model="form"
               :before-close="beforeClose"
               :before-open="beforeOpen"
               :data="data"
               :option="option"
               :page.sync="page"
               :permission="permissionList"
               :table-loading="loading"
               :upload-after="uploadAfter"
               :upload-delete="uploadDelete"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button v-if="permission.certificate_delete"
                   icon="el-icon-delete"
                   plain
                   size="small"
                   type="danger"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/certificate/certificate";
import {deleteAttach, getCertificateAttach} from "@/api/oss/attach";
import {mapGetters} from "vuex";
import {date} from "mockjs/src/mock/random/date";

export default {
  data() {
    return {
      attachId: [],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: "资质名称",
            prop: "certificateName",
            search: true,
            rules: [{
              required: true,
              message: "请输入资质名称",
              trigger: "blur"
            }]
          },
          {
            label: "资质类别",
            prop: "certificateType",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=certificate_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [{
              required: true,
              message: "请选择资质类别",
              trigger: "blur"
            }]
          },
          {
            label: "发证时间",
            prop: "certificateTime",
            type: "date",
            rules: [{
              required: true,
              message: "请选择发证时间",
              trigger: "blur"
            }]
          },
          {
            label: "有效日期",
            prop: "certificateStartTimeAndEndTime",
            type: "daterange",
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            change: (value) => {
              this.changeContractTime(value);
            },
            formatter: (row, column) => {
              if (row.startTime) {
                return row.startTime + "至" + row.endTime;
              }
            },
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            rules: [{
              required: true,
              message: "请选择有效日期",
              trigger: "blur"
            }]
          },
          {
            label: "资质描述",
            prop: "certificateRemark",
          },
          {
            label: '资质附件',
            prop: 'array',
            type: 'upload',
            hide: true,
            span: 24,
            dragFile: true,
            action: "/api/blade-oss/oss/endpoint/put-file-attach",
            propsHttp: {
              res: 'data',
              url: 'link',
              name: "originalName",
              info:"name"
              // home: this.$store.state.common.home
            },
            rules: [{
              required: true,
              message: "请上传资质附件",
              trigger: "blur"
            }]
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.certificate_add, false),
        viewBtn: this.vaildData(this.permission.certificate_view, false),
        delBtn: this.vaildData(this.permission.certificate_delete, false),
        editBtn: this.vaildData(this.permission.certificate_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    uploadAfter(res, done, loading, column) {
      console.log(res)
      this.attachId.push(res.attachId)
      console.log(this.attachId)
      done();
    },
    rowSave(row, done, loading) {
      if (this.attachId.length > 0) {
        row.imgUrl = this.attachId.join(",")
      }
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      console.log()
      if (this.attachId.length > 0) {
        row.imgUrl = this.attachId.join(",")
      }
      console.log(row.imgUrl)
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.certificateStartTimeAndEndTime = [];
          this.form.certificateStartTimeAndEndTime[0] = this.form.startTime;
          this.form.certificateStartTimeAndEndTime[1] = this.form.endTime;
        });
        getCertificateAttach(this.form.id).then(res => {
          res.data.data.forEach(item => {
            console.log(item.link.split("?")[0])
            this.form.array.push({
              "label": item.originalName,
              "value": item.link.split("?")[0],
              "info":item.name
            })
            console.log(this.form)
          })

        })
      }
      done();
    },
    beforeClose(done) {
      this.attachId = []
      done();
    },
    uploadDelete(file,row,column) {
      console.log(file)
      deleteAttach(file.url).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    changeContractTime(val) {
      if (val.value) {
        this.form.startTime = val.value[0];
        this.form.endTime = val.value[1];
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
